package com.levi.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.levi.domain.Permission;
import com.levi.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author shentong
 * @date 2021/10/26 21:58
 * @Description fixme 该类实现UserDetailsService接口，实现认证和授权
 */
@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LambdaQueryWrapper<User> lw = new LambdaQueryWrapper<>();
        lw.eq(User::getUsername, username);
        User user = userService.getOne(lw);
        if (user==null) {
            return null;
        }

        List<Permission> permissionListByUsername = permissionService.getPermissionListByUsername(username);
        List<String> permissionList = new ArrayList<>();

        permissionListByUsername.forEach(p -> permissionList.add(p.getCode()));
        String[] permissionArray = new String[permissionList.size()];
        permissionList.toArray(permissionArray);
        return org.springframework.security.core.userdetails.User.withUsername(user.getUsername()).password(user.getPassword()).authorities(permissionArray).build();
    }
}
